package com.kws.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.core.domain.R;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.Device;
import com.kws.merchant.domain.DeviceRemark;
import com.kws.merchant.domain.Order;
import com.kws.merchant.domain.Serve;
import com.kws.merchant.domain.po.GoodsRemarkPo;
import com.kws.merchant.domain.po.UserRemarkPo;
import com.kws.merchant.domain.vo.GoodsRemarkTagVo;
import com.kws.merchant.domain.vo.UserRemarkVo;
import com.kws.merchant.mapper.DeviceRemarkMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.RemoteUserService;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/11/7 15:02
 * @Version: 1.0
 */
@Service
public class UserRemarkServiceImpl implements UserRemarkService {

    @Autowired
    private DeviceRemarkService deviceRemarkService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceRemarkMapper deviceRemarkMapper;

    @Autowired
    private ServeService serveService;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUserRemark(UserRemarkPo userRemarkPo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long orderId = userRemarkPo.getOrderId();
        //判断是否已评价
        DeviceRemark deviceRemark = new DeviceRemark();
        Order order = orderService.getById(orderId);
        deviceRemark.setMerchantId(order.getMerchantId());
        deviceRemark.setOrderId(orderId);
        if (order.getIsEvaluate().equals(1)) {
            throw new RuntimeException("该订单已评价，请勿重复操作！");
        }
        if (userRemarkPo.getStarLevel() <= 2) {
            deviceRemark.setTag(5);
        } else if (userRemarkPo.getStarLevel() >= 4) {
            deviceRemark.setTag(4);
        } else if (3 == userRemarkPo.getStarLevel()) {
            deviceRemark.setTag(1);
        }
        deviceRemark.setPid(0L);
        deviceRemark.setScore(Double.valueOf(userRemarkPo.getStarLevel()));
        deviceRemark.setDeliveryPersonnel(userRemarkPo.getDeliveryPersonnel());
        deviceRemark.setDeliverySpeed(userRemarkPo.getDeliverySpeed());
        deviceRemark.setExpressPackage(userRemarkPo.getExpressPackage());
        deviceRemark.setRemarkType(userRemarkPo.getGoodsType().toString());
        deviceRemark.setRemark(userRemarkPo.getRemark());
        deviceRemark.setStarLevel(userRemarkPo.getStarLevel());
        deviceRemark.setDeviceId(userRemarkPo.getGoodsId());
        deviceRemark.setObserver(sysUser.getUserId());
        deviceRemark.setCreateUser(sysUser.getUserName());
        deviceRemark.setObserverPhone(sysUser.getPhonenumber());
        deviceRemark.setEnable("1");
        List<String> remarkImg = userRemarkPo.getRemarkImg();
        if (remarkImg != null && remarkImg.size() > 0){
            StringBuilder sb = new StringBuilder();
            for (String s : remarkImg) {
                String subFileName = fileUtil.subFileName(s);
                sb.append(subFileName).append("kws:");
            }
            deviceRemark.setRemarkImg(sb.substring(0, sb.length() - 4));
        }
        if (deviceRemarkService.save(deviceRemark)) {
            order.setIsEvaluate(1);
            return orderService.saveOrUpdate(order);
        }
        return false;
    }

    @Override
    public Page<UserRemarkVo> getUserRemarkList(UserRemarkPo userRemarkPo) {
        userRemarkPo.setPageSize((userRemarkPo.getPageSize() - 1) * userRemarkPo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<DeviceRemark> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DeviceRemark::getObserver, userId);
        wrapper.eq(DeviceRemark::getEnable, 1);
        long count = deviceRemarkService.count(wrapper);
        Page<UserRemarkVo> page = new Page<>(userRemarkPo.getPageSize(), userRemarkPo.getTotalPage(), count);
        if (count > 0) {
            List<UserRemarkVo> userRemarkList = deviceRemarkMapper.getUserRemarkList(userId, userRemarkPo.getPageSize(), userRemarkPo.getTotalPage());
            Map<Integer, List<UserRemarkVo>> listMap = userRemarkList.stream().collect(Collectors.groupingBy(UserRemarkVo::getGoodsType));
            List<UserRemarkVo> userRemarkVos = listMap.get(0);
            if (userRemarkVos != null && userRemarkVos.size() > 0) {
                List<Long> goodsIds = userRemarkVos.stream().map(UserRemarkVo::getGoodsId).collect(Collectors.toList());
                List<Device> deviceList = deviceService.list(Wrappers.<Device>lambdaQuery().in(Device::getId, goodsIds));
                Map<Long, Device> longDeviceMap = deviceList.stream()
                        .collect(Collectors.toMap(Device::getId, Function.identity()));
                for (UserRemarkVo userRemarkVo : userRemarkVos) {
                    Device device = longDeviceMap.get(userRemarkVo.getGoodsId());
                    userRemarkVo.setGoodsName(device.getName());
                    userRemarkVo.setGoodsImg(FileUtil.fixFileName() + device.getImg());
                    userRemarkVo.setRemark(device.getRemark());
                    String remarkImg = userRemarkVo.getRemarkImg();
                    List<String> remarkImgList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(remarkImg)) {
                        String[] imgs = remarkImg.split("kws:");
                        for (String img : imgs) {
                            String s = FileUtil.fixFileName() + img;
                            remarkImgList.add(s);
                        }
                    }
                    userRemarkVo.setRemarkImgList(remarkImgList);
                }
            }
            List<UserRemarkVo> userServeRemarkVos = listMap.get(1);
            if (userServeRemarkVos != null && userServeRemarkVos.size() > 0) {
                List<Long> goodsIds = userServeRemarkVos.stream().map(UserRemarkVo::getGoodsId).collect(Collectors.toList());
                List<Serve> serveList = serveService.list(Wrappers.<Serve>lambdaQuery().in(Serve::getId, goodsIds));
                Map<Long, Serve> longServeMap = serveList.stream()
                        .collect(Collectors.toMap(Serve::getId, Function.identity()));
                for (UserRemarkVo userRemarkVo : userServeRemarkVos) {
                    Serve serve = longServeMap.get(userRemarkVo.getGoodsId());
                    userRemarkVo.setGoodsName(serve.getName());
                    userRemarkVo.setGoodsImg(FileUtil.fixFileName() + serve.getImg());
                    userRemarkVo.setRemark(serve.getRemark());
                    String remarkImg = userRemarkVo.getRemarkImg();
                    List<String> remarkImgList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(remarkImg)) {
                        String[] imgs = remarkImg.split("kws:");
                        for (String img : imgs) {
                            String s = FileUtil.fixFileName() + img;
                            remarkImgList.add(s);
                        }
                    }
                    userRemarkVo.setRemarkImgList(remarkImgList);
                }
            }
            page.setRecords(userRemarkList);
        }
        return page;
    }

    @Override
    public List<DeviceRemark> getUserRemarkInfo(Long goodsId) {
        List<DeviceRemark> remarkByDeviceId = deviceRemarkService.getRemarkByDeviceId(goodsId);
        if (ObjectUtils.isNotNull(remarkByDeviceId)) {
            return remarkByDeviceId;
        }
        return null;
    }

    @Override
    public boolean deleteUserRemark(Long remarkId) {
        DeviceRemark byId = deviceRemarkService.getById(remarkId);
        if (ObjectUtils.isNull(byId)) return false;
        byId.setEnable("0");
        return deviceRemarkService.save(byId);
    }

    @Override
    public Page<UserRemarkVo> getGoodsRemarkList(GoodsRemarkPo goodsRemarkPo) {
        goodsRemarkPo.setPageSize((goodsRemarkPo.getPageSize() - 1) * goodsRemarkPo.getTotalPage());
        Integer count = deviceRemarkMapper.getGoodsRemarkCount(goodsRemarkPo.getGoodsId(), goodsRemarkPo.getTag(), goodsRemarkPo.getRemarkType());
        Page<UserRemarkVo> page = new Page<>(goodsRemarkPo.getPageSize(), goodsRemarkPo.getTotalPage(), count);
        if (count > 0) {
            List<UserRemarkVo> goodsRemarkList = deviceRemarkMapper.getGoodsRemarkList(
                    goodsRemarkPo.getGoodsId(), goodsRemarkPo.getTag(), goodsRemarkPo.getRemarkType(),
                    goodsRemarkPo.getPageSize(), goodsRemarkPo.getTotalPage());
            List<Long> goodsIds = goodsRemarkList.stream().map(UserRemarkVo::getGoodsId).collect(Collectors.toList());
            if (goodsRemarkList.get(0).getGoodsType().equals(0)) {
                List<Device> deviceList = deviceService.list(Wrappers.<Device>lambdaQuery().in(Device::getId, goodsIds));
                Map<Long, Device> longDeviceMap = deviceList.stream()
                        .collect(Collectors.toMap(Device::getId, Function.identity()));
                for (UserRemarkVo userRemarkVo : goodsRemarkList) {
                    Device device = longDeviceMap.get(userRemarkVo.getGoodsId());
                    userRemarkVo.setGoodsName(device.getName());
                    userRemarkVo.setGoodsImg(FileUtil.fixFileName() + device.getImg());
                    userRemarkVo.setRemark(device.getRemark());
                    String remarkImg = userRemarkVo.getRemarkImg();
                    List<String> remarkImgList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(remarkImg)) {
                        String[] imgs = remarkImg.split("kws:");
                        for (String img : imgs) {
                            String s = FileUtil.fixFileName() + img;
                            remarkImgList.add(s);
                        }
                        userRemarkVo.setRemarkImgList(remarkImgList);
                    }
                }
                page.setRecords(goodsRemarkList);
                return page;
            } else {
                List<Serve> serveList = serveService.list(Wrappers.<Serve>lambdaQuery().in(Serve::getId, goodsIds));
                Map<Long, Serve> longServeMap = serveList.stream()
                        .collect(Collectors.toMap(Serve::getId, Function.identity()));
                for (UserRemarkVo userRemarkVo : goodsRemarkList) {
                    Serve serve = longServeMap.get(userRemarkVo.getGoodsId());
                    userRemarkVo.setGoodsName(serve.getName());
                    userRemarkVo.setGoodsImg(FileUtil.fixFileName() + serve.getImg());
                    userRemarkVo.setRemark(serve.getRemark());
                    String remarkImg = userRemarkVo.getRemarkImg();
                    List<String> remarkImgList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(remarkImg)) {
                        String[] imgs = remarkImg.split("kws:");
                        for (String img : imgs) {
                            String s = FileUtil.fixFileName() + img;
                            remarkImgList.add(s);
                        }
                    }
                    userRemarkVo.setRemarkImgList(remarkImgList);
                }
                page.setRecords(goodsRemarkList);
                return page;
            }
        }
        return page;
    }

    @Override
    public GoodsRemarkTagVo getGoodsRemarkTagCount(Long goodsId) {
        //获取用户对设备的评论
        LambdaQueryWrapper<DeviceRemark> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DeviceRemark::getDeviceId, goodsId);
        wrapper.eq(DeviceRemark::getEnable, "1");
        wrapper.eq(DeviceRemark::getPid, 0L);
        List<DeviceRemark> list = deviceRemarkService.list(wrapper);
        GoodsRemarkTagVo goodsRemarkTagVo = new GoodsRemarkTagVo();
        if (ObjectUtils.isNotNull(list)) {
            Map<Integer, List<DeviceRemark>> listMap = list.stream().collect(Collectors.groupingBy(DeviceRemark::getTag));
            goodsRemarkTagVo.setTotal(list.size());
            goodsRemarkTagVo.setNotBad(listMap.getOrDefault(0, Collections.emptyList()).size());
            goodsRemarkTagVo.setGeneral(listMap.getOrDefault(1, Collections.emptyList()).size());
            goodsRemarkTagVo.setImage(listMap.getOrDefault(2, Collections.emptyList()).size());
            goodsRemarkTagVo.setFollow(listMap.getOrDefault(3, Collections.emptyList()).size());
            goodsRemarkTagVo.setGood(listMap.getOrDefault(4, Collections.emptyList()).size());
            goodsRemarkTagVo.setBad(listMap.getOrDefault(5, Collections.emptyList()).size());
        }
        return goodsRemarkTagVo;
    }


}
